package com.wk.masterNode;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;


import com.wk.constains.net.SendUtils;
import com.wk.database.DB_Mysql;
import com.wk.database.IdToMachine;
import com.wk.job.Job;

/***
 * 任务的分发策略
 * 
 * @author wkhua
 *
 */
public class DistrubuteJob {
	@Deprecated
	private Map<String, String> idAndMachine =null;
	private IdToMachine idToMachine = null;
	private LinkedBlockingQueue<Job> jobsqueue = null;
	private ConcurrentHashMap<String, Job> distributedjobsMap =null;
	 
	/***
	 * 初始化状态：
	 * 1. jobsqueue 待分发job
	 * 2. idAndMachine 映射关系表
	 * @param jobsqueue 待分发的任务
	 * @param distributedjobsMap  已分发成功的jobsmap (key: job.getJobId() ,value: Job)
	 * @param distributejob 分发关系表
	 */
	@Deprecated
	public DistrubuteJob (LinkedBlockingQueue<Job> jobsqueue, Map<String, String> idAndMachine, ConcurrentHashMap<String, Job> distributedjobsMap){
		this.jobsqueue = jobsqueue;
		this.idAndMachine = idAndMachine;
		this.distributedjobsMap = distributedjobsMap;
	}
	public DistrubuteJob (LinkedBlockingQueue<Job> jobsqueue, IdToMachine idToMachine, ConcurrentHashMap<String, Job> distributedjobsMap){
		this.jobsqueue = jobsqueue;
		this.idToMachine = idToMachine;
		this.distributedjobsMap = distributedjobsMap;
	}
	
	/***
	 * 向从机发送一个任务
	 * 1. 在jobsqueue中获取一个job
	 * 2. 提取ip信息发送给从机
	 * 3. 成功发送则把任务添加到distributedjobsMap中
	 * 
	 * @return
	 */
	public boolean distributeAJob(){
		Job job = null;
		try {
			job = jobsqueue.take();//获取待处理的一个job。如果不存在就阻塞。
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd E HH:mm:ss");
			String  jobDistributeTime =  sdf.format(new Date());//时间
			job.setJobDistributeTime(jobDistributeTime);
			
			String name = job.getJobAddress();
			String address = idToMachine.get(name);
		//	String address = idAndMachine.get(name);
			if(address == null){
				return false ;
			}
			String[] ip_and_port = address.split(":");
			
			int port = 8080;
			if(ip_and_port.length != 2 && ip_and_port.length == 1){
				SendUtils.sendJob(ip_and_port[0], port, job);
			}else{
				SendUtils.sendJob(ip_and_port[0], Integer.valueOf(ip_and_port[1]), job);
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		if(job != null){
			DB_Mysql.setDistributed(job.getTaskId());
			distributedjobsMap.put( job.getId() , job );
		}
		return true;
	}
	
	
	
}
